package com.cj.servlet;

import com.cj.entity.Employee;
import com.cj.servcie.EmployeeService;
import com.cj.servcie.impl.EmployeeServiceImpl;
import com.cj.utils.PageBean;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/employee")
//处理员工管理相关操作的类
public class EmployeeServlet extends HttpServlet {
    //处理不同的员工管理操作
    private EmployeeService empService = new EmployeeServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("UTF-8");
        //设置响应编码
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("进入employeeServlet");
        //获取请求参数方法，用于判断执行哪种操作
        String method = request.getParameter("method");
        int page = 1;
        if (request.getParameter("page") != null && !request.getParameter("page").equals("")) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        //根据method值执行不同的操作
        switch (method) {
            case "empList":
                //查询员工列表信息方法
                selectEmployeeList(request, response, page);
                break;
            case "addEmployee":
                //添加员工信息方法
                addEmployee(request, response);
                //重定向到员工列表页面
                response.sendRedirect("employee?method=empList");
                break;
            case "updateEmployee":
                //修改员工信息方法
                updateEmployee(request, response);
                //重定向到员工列表页面
                response.sendRedirect("employee?method=empList");
                break;
            case "deleteEmployee":
                //删除员工信息方法
                deleteEmployee(request, response);
                break;
            default:
                //默认情况，打印空信息
                System.out.println("");
                break;
        }
    }

    /**
     * 查询员工列表信息的方法
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws ServletException 如果Servlet遇到异常
     * @throws IOException      如果发生输入或输出异常
     */
    private void selectEmployeeList(HttpServletRequest request, HttpServletResponse response, int page) throws ServletException, IOException {
        //通过empService获取employee所有列表信息
        PageBean<Employee> empListBypage = empService.empListBypage(page);
        List<Employee> empList = empListBypage.getList();
        //关闭数据库连接
        empService.closeConn();
        //将员工列表信息放入请求属性中
        request.setAttribute("empList", empList);
        //将当前页码放入请求属性中
        request.setAttribute("page", String.valueOf(page));
        //将总页数放入请求属性中
        request.setAttribute("totalPage", String.valueOf(empListBypage.getTotalPage()));

        //请求转发到员工管理列表界面
        try {
            // 转发请求到 employee.jsp 页面
            request.getRequestDispatcher("employee.jsp").forward(request, response);
        } catch (ServletException | IOException e) {
            // 记录异常信息
            e.printStackTrace();
        }
    }

    /**
     * 删除员工信息方法
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws ServletException 如果Servlet遇到异常
     * @throws IOException      如果发生输入或输出异常
     */
    private void deleteEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端表单提交的id值，默认为字符串
        String id_str = request.getParameter("id");
        int id = Integer.parseInt(id_str);
        //根据id查询员工信息是否存在，如果存在，就删除，如果不存在，返回错误信息
        Employee employee = empService.getEmployeeById(id);
        //结果返回对象
        Result result = new Result();

        String jsonStr = "";
        if (employee == null) {
            //用户不存在，设置返回码和消息
            result.setCode(201);
            result.setMessage("用户不存在！");
            jsonStr = JSONArray.fromObject(result).toString();
            //将结果集以JSON字符串的格式通过response传给前端
            response.getWriter().write(jsonStr);
            return;
        }
        //用户存在，执行删除操作
        int delResult = empService.deleteEmployee(id);
        if (delResult == 0) {
            //删除失败，设置返回码和消息
            result.setCode(202);
            result.setMessage("用户删除失败！");
        } else {
            //删除成功，设置消息
            result.setMessage("已成功删除员工信息！");
        }

        jsonStr = JSONArray.fromObject(result).toString();
        //将结果写入响应
        response.getWriter().write(jsonStr);
    }

    /**
     * 添加员工信息
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws ServletException 如果Servlet遇到异常
     * @throws IOException      如果发生输入或输出异常
     */
    private void addEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取表单提交的员工信息
        String workNo = request.getParameter("workNo");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String age_str = request.getParameter("age");
        int age = Integer.parseInt(age_str);
        String idCard = request.getParameter("idCard");
        String workAddress = request.getParameter("workAddress");

        //创建员工对象
        Employee emp = new Employee(workNo, name, gender, age, idCard, workAddress, new Date());
        //执行添加操作
        int result = empService.addEmployee(emp);

        //创建用于返回结果的Map对象
        Map<String, Object> maps = new HashMap<>();
        if (result == 1) {
            //添加成功，设置消息和状态码
            maps.put("message", "员工信息添加成功！");
            maps.put("status", 200);
        } else {
            //添加失败，设置消息和状态码
            maps.put("message", "员工信息添加失败！");
            maps.put("status", 400);
        }

        //将结果集转为JSON字符串并写入响应
        String rst = JSONArray.fromObject(maps).toString();
        response.getWriter().write(rst);
    }

    /**
     * 修改员工信息
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws ServletException 如果Servlet遇到异常
     * @throws IOException      如果发生输入或输出异常
     */
    private void updateEmployee(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取表单提交的员工信息
        String id_str = request.getParameter("id");
        int id = Integer.parseInt(id_str);
        String workNo = request.getParameter("workNo");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String age_str = request.getParameter("age");
        int age = Integer.parseInt(age_str);
        String idCard = request.getParameter("idCard");
        String workAddress = request.getParameter("workAddress");

        //创建员工对象
        Employee employee = new Employee(id, workNo, name, gender, age, idCard, workAddress);
        //执行修改操作
        int result = empService.updateEmployee(employee);
        if (result == 1) {
            //修改成功，设置成功消息
            request.setAttribute("sucessMsg", "员工信息修改成功！");
        } else {
            //修改失败，设置错误消息
            request.setAttribute("errMessage", "员工信息修改失败！");
        }
    }
}
